package com.veryUsedCar.shiro;

import com.veryUsedCar.api.UserServiceApi;
import com.veryUsedCar.data.Result;
import com.veryUsedCar.dto.UserDTO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class LoginRealm  extends AuthorizingRealm {
    @Autowired
    private UserServiceApi userServiceApi;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权方法");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //获取当前登录的用户
        UserDTO user = (UserDTO) SecurityUtils.getSubject().getPrincipal();
        //根据用户的id查询用户权限字符串
        //List<String> perms = menuServiceI.selectPermsByPersonId(person.getPid());
        //info.addStringPermissions(perms);
        return info;
    }

    @Override
    protected SimpleAuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//        System.out.println("认证方法");
//        String pname = "admin";
//        String pwd = "1cbec737e5a91d938d1a2cf6cbacf192";
//        String salt = "53c7ab";

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String uname = token.getUsername();
        Result<UserDTO> user = userServiceApi.findUserByName(uname);
        if (user == null ){
            return null;
        }

        //第一个参数:登录成功后放到session中的用户对象, 第二个参数:数据库密码 需要校验用, 第三个是盐, 第四个参数:登录成功后的用户账号
        return new SimpleAuthenticationInfo(user,user.getData().getPassword(), ByteSource.Util.bytes(user.getData().getSalt()),user.getData().getUname());
    }
}
